package com.liuyongyi.livepush.camerapush;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;

import com.liuyongyi.livepush.camerapush.natives.PusherNative;

/**
 * Created by liuyongyi on 2017/12/31.
 */

public class AudioPusher extends IPusher {
    private AudioParms audioParms;
    private AudioRecord audioRecord;
    private boolean isPusher = false;
    private  int minBuffersize;
    private PusherNative pusherNative;

    public AudioPusher(AudioParms audioParms, PusherNative pusherNative) {
        this.audioParms = audioParms;
        this.pusherNative = pusherNative;
        int channerconfig = audioParms.getChannel() ==1?AudioFormat.CHANNEL_IN_MONO:AudioFormat.CHANNEL_IN_STEREO;
        minBuffersize = AudioRecord.getMinBufferSize(audioParms.getSampleRateInHz(),channerconfig,AudioFormat.ENCODING_PCM_16BIT);
        audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
                audioParms.getSampleRateInHz(),
                channerconfig,
                AudioFormat.ENCODING_PCM_16BIT,minBuffersize);

    }

    @Override
    public void startPusher() {
        pusherNative.setAudioOptions(audioParms.getSampleRateInHz(),audioParms.getChannel());
        //启动一个录音的主线程
        isPusher= true;
        new Thread(new AudioRecordTask()).start();
    }

    @Override
    public void stopPusher() {
        isPusher= false;
        audioRecord.stop();
    }

    @Override
    public void release() {
        if(audioRecord != null){
            audioRecord.release();
            audioRecord = null;
        }
    }

    class AudioRecordTask implements Runnable{

        @Override
        public void run() {
            //开始录音
            audioRecord.startRecording();
            while (isPusher){
                //通过AudioRecord不断的读取音频数据
                byte[] buffer = new byte[minBuffersize];
                int leng = audioRecord.read(buffer,0,buffer.length);
                if(leng > 0){
                    //传递给native进行音频编码
                    pusherNative.sendAudio(buffer,leng);
                }
            }
        }
    }
}
